package com.mobilepay.moneypig.model.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.loonggg.rvbanner.lib.RecyclerViewBanner;
import com.mobilepay.moneypig.R;
import com.mobilepay.moneypig.base.BaseFragment;
import com.mobilepay.moneypig.config.Key;
import com.mobilepay.moneypig.config.NetConfig;
import com.mobilepay.moneypig.model.activity.home.CollectMoneyActivity;
import com.mobilepay.moneypig.model.activity.home.ListApplyCreditActivity;
import com.mobilepay.moneypig.model.activity.home.ListApplyMoneyActivity;
import com.mobilepay.moneypig.model.activity.launcher.MainActivity;
import com.mobilepay.moneypig.model.activity.mine.AddCardActivity;
import com.mobilepay.moneypig.model.activity.mine.IdentifyActivity;
import com.mobilepay.moneypig.model.activity.mine.NotesActivity;
import com.mobilepay.moneypig.model.activity.mine.UserInfoActivity;
import com.mobilepay.moneypig.model.activity.scan.ScanActivity;
import com.mobilepay.moneypig.model.application.App;
import com.mobilepay.moneypig.model.dialog.TipDialog;
import com.mobilepay.moneypig.okhttp.HttpUtils;
import com.mobilepay.moneypig.response.ResponseResult;
import com.mobilepay.moneypig.response.home.HomeData;
import com.mobilepay.moneypig.utils.CommonUtil;
import com.mobilepay.moneypig.utils.GsonUtil;
import com.mobilepay.moneypig.utils.acache.ACache;
import com.mobilepay.moneypig.view.MarqueeTextView;
import com.mobilepay.moneypig.view.WebViewActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xlm on 2017/7/14 0014
 */

public class HomePageFragment extends BaseFragment {

    private static final String TAG = "HomePageFragment";
    private SmartRefreshLayout refreshLayout;
    private List<HomeData.Data.Carousel> carousels;
    private List<HomeData.Data.Menu> menus;
    private List<HomeData.Data.Ad> ads;
    private List<HomeData.Data.Notice> mNotices;
    private RecyclerView mRecycleView;
    private RelativeLayout mImageNotes;
    private RelativeLayout mImageQrcode;
    private RelativeLayout mImageUserinfo;
    private RecyclerViewBanner mRecycleBanner;
    private MarqueeTextView marqueeTv;
    private List<String> mStringTitle;
    private List<String> mStringUrl;

    @Override
    protected void onSetContentView() {
        setContentView(R.layout.fragment_home);
    }

    @Override
    protected void initViews() {
        marqueeTv = (MarqueeTextView) mLayoutView.findViewById(R.id.marqueeTv);
        refreshLayout = (SmartRefreshLayout) mLayoutView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableLoadmore(false);
        mRecycleView = (RecyclerView) mLayoutView.findViewById(R.id.home_recycle);
        mImageNotes = (RelativeLayout) mLayoutView.findViewById(R.id.home_notes);
        mImageQrcode = (RelativeLayout) mLayoutView.findViewById(R.id.home_qrcode);
        mImageUserinfo = (RelativeLayout) mLayoutView.findViewById(R.id.home_userinfo);
        mRecycleBanner = (RecyclerViewBanner) mLayoutView.findViewById(R.id.rv_banner);
        mRecycleBanner.isShowIndicator(true);
    }

    @Override
    protected void afterOnCreate(Bundle savedInstanceState) {
        startRecycleBanner();
        setHomeAdapter();
        getHomeData();//获取首页数据
    }

    @Override
    public void onDestroy() {
        marqueeTv.releaseResources();
        super.onDestroy();
    }

    public static final int REQUST_QRCODE = 1;
    private static final int PERMISSON_CAMER = 1;

    /**
     * 检查权限，因为android6.0有些权限需要用户确认授权
     */

    private void checkPermission() {
        if (checkCameraPermission(PERMISSON_CAMER)) {
            Intent intent = new Intent();
            intent.setClass(getActivity(), ScanActivity.class);
            startActivityForResult(intent, REQUST_QRCODE);
        }
    }

    @Override
    public void onCameraPermission(int result_code, boolean result) {
        if (result) {
            checkPermission();
        } else {
            showToastShort("拒绝此权限，您将无法使用相机功能");
        }
    }

    @Override
    protected void onSetListener() {

        mImageUserinfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(UserInfoActivity.class);
            }
        });
        mImageQrcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkPermission();
            }
        });
        mImageNotes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(NotesActivity.class);
            }
        });

        homeAdapter.setHomeItemClickListener(new HomeAdapter.OnHomeClickListener() {
            @Override
            public void onClick(View item, int position, String url, String type) {
                int realStatus = App.getApp().getUserDetailInfo().getData().getReal_auth_status();
                int bankStatus = App.getApp().getUserDetailInfo().getData().getBank_auth_status();
                if ("menu".equals(type)) {
                    if (CommonUtil.checkURL(url)) {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), WebViewActivity.class);
                        intent.putExtra(Key.URL, url);
                        startActivity(intent);
                    } else {
                        if (position == 0) {
                            if (realStatus == 0) {
                                showConfirm("请先进行实名认证");
                            } else if (realStatus == 1) {
                                showToastShort("认证审核中");
                            } else if (realStatus == 2) {
                                if (bankStatus == 1) {
                                    startActivity(CollectMoneyActivity.class);
                                } else {
                                    showCardConfirm("请先绑定结算卡");
                                }
                            } else {
                                showConfirm("请先进行实名认证");
                            }
                        } else if (position == 1) {
                            if (realStatus == 0) {
                                showConfirm("请先进行实名认证");
                            } else if (realStatus == 1) {
                                showToastShort("认证审核中");
                            } else if (realStatus == 2) {
                                startActivity(ListApplyCreditActivity.class);
                            } else {
                                showConfirm("请先进行实名认证");
                            }
                        } else if (position == 2) {
                            if (realStatus == 0) {
                                showConfirm("请先进行实名认证");
                            } else if (realStatus == 1) {
                                showToastShort("认证审核中");
                            } else if (realStatus == 2) {
                                startActivity(ListApplyMoneyActivity.class);
                            } else {
                                showConfirm("请先进行实名认证");
                            }
                        } else {
                            showToastShort("敬请期待");
                        }
                    }
                } else if ("ads".equals(type)) {
                    if (CommonUtil.checkURL(url)) {
                        Intent intent = new Intent();
                        intent.setClass(getActivity(), WebViewActivity.class);
                        intent.putExtra(Key.URL, url);
                        startActivity(intent);
                    } else {
                        showToastShort("敬请期待");
//                        if (position == 0) {
//                            startActivity(GroupActivity.class);
//                        } else {
//                            showToastShort("敬请期待");
//                        }
                    }
                }
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getHomeData();
                ((MainActivity) getActivity()).checkVersonUpdate();
            }
        });
    }

    private TipDialog confirmDialog;

    private void showConfirm(String txt) {
        if (confirmDialog == null) {
            confirmDialog = new TipDialog(getActivity());
        }
        confirmDialog.setContent(txt);
        confirmDialog.setCancelable(true);
        confirmDialog.setConfirm("去认证");
        confirmDialog.show();
        confirmDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmDialog.dismiss();
                startActivity(IdentifyActivity.class);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmDialog.dismiss();
            }
        });
    }

    private TipDialog confirmCardDialog;

    private void showCardConfirm(String txt) {
        if (confirmCardDialog == null) {
            confirmCardDialog = new TipDialog(getActivity());
        }
        confirmCardDialog.setContent(txt);
        confirmCardDialog.setCancelable(true);
        confirmCardDialog.setConfirm("去绑定");
        confirmCardDialog.show();
        confirmCardDialog.setListener(new TipDialog.Listener() {
            @Override
            public void onConfirm() {
                super.onConfirm();
                confirmCardDialog.dismiss();
                startActivity(AddCardActivity.class);
            }

            @Override
            public void onDismiss() {
                super.onDismiss();
                confirmCardDialog.dismiss();
            }
        });
    }

    private HomeAdapter homeAdapter;

    private void setHomeAdapter() {
        menus = new ArrayList<>();
        ads = new ArrayList<>();
        mNotices = new ArrayList<>();
        mStringTitle = new ArrayList<>();
        mStringUrl = new ArrayList<>();
        homeAdapter = new HomeAdapter(getActivity());
        homeAdapter.setData(menus, ads);
        mRecycleView.setLayoutManager(new GridLayoutManager(getActivity(), 6));
        mRecycleView.setAdapter(homeAdapter);
    }

    private static class HomeAdapter extends RecyclerView.Adapter {
        private static final int TYPE_MENU = 1;
        private static final int TYPE_ADS = 2;
        private LayoutInflater layoutInflater;
        private List<HomeData.Data.Menu> menus;
        private List<HomeData.Data.Ad> ads;

        public HomeAdapter(Context context) {
            layoutInflater = LayoutInflater.from(context);
        }

        public void setData(List<HomeData.Data.Menu> menus, List<HomeData.Data.Ad> ads) {
            this.menus = menus;
            this.ads = ads;
        }

        @Override
        public int getItemViewType(int position) {
            if (menus.size() != 0 && (position <= menus.size() - 1)) {
                return TYPE_MENU;
            }
            return TYPE_ADS;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_MENU) {
                return new MenuViewHolder(layoutInflater.inflate(R.layout.item_menu_home, parent, false));
            }
            return new AdsViewHolder(layoutInflater.inflate(R.layout.item_advace_home, parent, false));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof MenuViewHolder) {
                Glide.with(((MenuViewHolder) holder).mMenuImage.getContext())
                        .load(menus.get(position).getPath())
                        .placeholder(R.mipmap.icon)
                        .into(((MenuViewHolder) holder).mMenuImage);
                ((MenuViewHolder) holder).mMenuText.setText(menus.get(position).getTitle());
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onHomeClickListener.onClick(view, position, menus.get(position).getUrl(), "menu");
                    }
                });
            } else if (holder instanceof AdsViewHolder) {
                Glide.with(((AdsViewHolder) holder).mAdsIamge.getContext())
                        .load(ads.get(position - menus.size()).getPath())
                        .into(((AdsViewHolder) holder).mAdsIamge);
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onHomeClickListener.onClick(view, position - menus.size(), ads.get(position - menus.size()).getUrl(), "ads");
                    }
                });
            }
        }

        @Override
        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
            super.onAttachedToRecyclerView(recyclerView);
            final GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
            layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    if (position < menus.size()) {
                        return 2;
                    }
                    return 6;
                }
            });
        }

        @Override
        public int getItemCount() {
            return menus.size() + ads.size();
        }

        public void setHomeItemClickListener(OnHomeClickListener onHomeClickListener) {
            this.onHomeClickListener = onHomeClickListener;
        }

        private OnHomeClickListener onHomeClickListener;

        public interface OnHomeClickListener {
            void onClick(View item, int position, String url, String type);
        }
    }

    /**
     * RecyclerViewBanner使用
     */
    private void startRecycleBanner() {
        carousels = new ArrayList<>();
        mRecycleBanner.setRvBannerData(carousels);
        mRecycleBanner.setOnSwitchRvBannerListener(new RecyclerViewBanner.OnSwitchRvBannerListener() {
            @Override
            public void switchBanner(int i, AppCompatImageView appCompatImageView) {
                appCompatImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                Glide.with(appCompatImageView.getContext())
                        .load(carousels.get(i).getPath())
                        .placeholder(R.mipmap.default_lb)
                        .into(appCompatImageView);
            }
        });
        mRecycleBanner.setOnRvBannerClickListener(new RecyclerViewBanner.OnRvBannerClickListener() {
            @Override
            public void onClick(int i) {
                String url = carousels.get(i).getUrl();
                if (CommonUtil.checkURL(url)) {
                    Intent intent = new Intent();
                    intent.setClass(getActivity(), WebViewActivity.class);
                    intent.putExtra(Key.URL, url);
                    startActivity(intent);
                } else {
                    showToastShort("敬请期待");
                }
            }
        });
    }

    private void getHomeData() {
        HttpUtils.RequestParam param = new HttpUtils.RequestParam();
        param.add("method", NetConfig.getinfo);
        param.add("uid", App.getApp().getUserInfo().getData().getUid() + "");
        param.add("image_name", "carousel_menu_ad");
        param.add("sign", param.getMd5String());
        showProgress("加载中");
        HttpUtils.getInstance().params(param).executePost(new HttpUtils.HttpListener() {
            @Override
            public void onException(Throwable e) {
                super.onException(e);
                dismissProgress();
                if (refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh();
                }
                if (CommonUtil.isForeground(getActivity())) {
                    showToastShort(getString(R.string.net_state));
                    String jsonString = ACache.get(App.getApp()).getAsString(NetConfig.getinfo);
                    if (!CommonUtil.isEmpty(jsonString)) {
                        setHomeData(jsonString);
                    }
                }
            }

            @Override
            public void onHttpSuccess(final String string) {
                super.onHttpSuccess(string);
                dismissProgress();
                if (HttpUtils.isJson(string)) {
                    ResponseResult result = GsonUtil.GsonToBean(string, ResponseResult.class);
                    if (result.getStatus() == 1) {
                        setHomeData(string);
                        ACache.get(App.getApp()).put(NetConfig.getinfo, string);//保存json数据
                    } else {
                        showToastShort(result.getInfo());
                    }
                }
                if (refreshLayout.isRefreshing()) {
                    refreshLayout.finishRefresh();
                }
            }
        });
    }


    /**
     * 设置数据
     *
     * @param string
     */
    private void setHomeData(String string) {
        HomeData data = GsonUtil.GsonToBean(string, HomeData.class);
        ArrayList<HomeData.Data.Carousel> newCarousels = data.getData().getCarousel();
        ArrayList<HomeData.Data.Menu> newMenus = data.getData().getMenu();
        ArrayList<HomeData.Data.Ad> newAds = data.getData().getAd();
        ArrayList<HomeData.Data.Notice> notices = data.getData().getNotice();
        carousels.clear();
        menus.clear();
        ads.clear();
        mNotices.clear();
        mStringTitle.clear();
        mStringUrl.clear();
        carousels.addAll(newCarousels);
        menus.addAll(newMenus);
        ads.addAll(newAds);
        mNotices.addAll(notices);
        homeAdapter.setData(menus, ads);
        mHandler.sendEmptyMessage(CB_MENU_AD);//更新
    }

    private static final int CB_MENU_AD = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CB_MENU_AD:
                    mRecycleBanner.setRvBannerData(carousels);
                    mRecycleBanner.setOnSwitchRvBannerListener(new RecyclerViewBanner.OnSwitchRvBannerListener() {
                        @Override
                        public void switchBanner(int i, AppCompatImageView appCompatImageView) {
                            appCompatImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                            Glide.with(appCompatImageView.getContext())
                                    .load(carousels.get(i).getPath())
                                    .placeholder(R.mipmap.default_lb)
                                    .into(appCompatImageView);
                        }
                    });
                    mRecycleBanner.setOnRvBannerClickListener(new RecyclerViewBanner.OnRvBannerClickListener() {
                        @Override
                        public void onClick(int i) {
                            String url = carousels.get(i).getUrl();
                            if (CommonUtil.checkURL(url)) {
                                Intent intent = new Intent();
                                intent.setClass(getActivity(), WebViewActivity.class);
                                intent.putExtra(Key.URL, url);
                                startActivity(intent);
                            } else {
                                showToastShort("敬请期待");
                            }
                        }
                    });
                    homeAdapter.notifyDataSetChanged();
                    for (HomeData.Data.Notice notice : mNotices) {
                        mStringTitle.add(notice.getTitle());
                        mStringUrl.add(notice.getUrl());
                    }
                    marqueeTv.setTextArraysAndClickListener(mStringTitle.toArray(new String[mStringTitle.size()]),
                            mStringUrl.toArray(new String[mStringUrl.size()]), new MarqueeTextView.MarqueeTextViewClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String url = view.getTag().toString();
                                    if (CommonUtil.checkURL(url)) {
                                        Intent intent = new Intent();
                                        intent.setClass(getActivity(), WebViewActivity.class);
                                        intent.putExtra(Key.URL, url);
                                        startActivity(intent);
                                    }
                                }
                            });
                    break;
            }
        }
    };

    private static class MenuViewHolder extends RecyclerView.ViewHolder {
        private ImageView mMenuImage;
        private TextView mMenuText;

        public MenuViewHolder(View itemView) {
            super(itemView);
            mMenuImage = (ImageView) itemView.findViewById(R.id.menu_image);
            mMenuText = (TextView) itemView.findViewById(R.id.menu_txt);
        }
    }

    private static class AdsViewHolder extends RecyclerView.ViewHolder {
        private ImageView mAdsIamge;

        public AdsViewHolder(View itemView) {
            super(itemView);
            mAdsIamge = (ImageView) itemView.findViewById(R.id.advace_image);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK) {
            String result = data.getStringExtra("result");
            if (CommonUtil.checkURL(result)) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), WebViewActivity.class);
                intent.putExtra(Key.URL, result);
                startActivity(intent);
            } else {
                showToastShort(result);
            }
        }
    }
}
